package cn.regexp.service.impl;

import cn.regexp.domain.Order;
import cn.regexp.domain.Product;
import cn.regexp.feign.ProductFeignApi;
import cn.regexp.repository.OrderRepository;
import cn.regexp.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ProductFeignApi productFeignApi;

    @Override
    public Order get(Long userId, Long productId) {
        Order order = new Order();
        order.setNumber(1);
        order.setOid(1L);
        order.setUid(userId);
        order.setUsername("regexp");

        // 从 nacos 中获取指定服务名称的服务实例集合
        /*List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        int index = new Random().nextInt(instances.size());
        ServiceInstance instance = instances.get(index);*/

        // 从服务实例中获取服务地址
        // Product product = restTemplate.getForObject("http://product-service/get?id=" + productId, Product.class);
        Product product = productFeignApi.get(productId);
        order.setPid(productId);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        return order;
    }
}
